import { Message } from 'bi-element-ui';
import NProgress from 'nprogress'; // progress bar
import router from './router';
import store from './store';
import 'nprogress/nprogress.css'; // progress bar style
import { getToken } from '@/utils/auth'; // get token from cookie
import getPageTitle from '@/utils/get-page-title';

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['/login', '/sso']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // 切换页面的时候取消之前的页面请求
  if (store.state.user.axiosCancelList && store.state.user.axiosCancelList.length > 0) {
    const axiosCancelList = JSON.parse(JSON.stringify(store.state.user.axiosCancelList));
    axiosCancelList.forEach((e) => {
      console.log(e);
    });
    store.commit('user/set_axiosCancelList', axiosCancelList);
  }
  // start progress bar
  NProgress.start();
  // set page title
  document.title = getPageTitle(to.meta.title || store.getters.currentMenuRouter.name || '');

  // determine whether the user has logged in

  const hasToken = getToken();
  // debugger
  if (hasToken) {
    if (to.path === '/sso' && to.query.token) {
      next();
    } else if (to.path === '/login' || to.path === '/sso') {
      // if is logged in, redirect to the home page
      next({ path: '/' });
      NProgress.done();
    } else {
      const hasGetUserInfo = store.getters.name;
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo');
          await store.dispatch('user/getMenuRouter');
          // await store.dispatch('user/set_chatroom_auth')
          next();
        } catch (error) {
          // remove token and go to login page to re-login
          console.log(error);
          await store.dispatch('user/resetToken');
          Message.error(error.msg || 'Has Error');
          next(`/sso?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token */
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/sso?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
